package com.dk.nfc.Card;

import android.nfc.tech.NfcB;

import com.dk.nfc.Exception.CardNoResponseException;
import com.dk.nfc.DeviceManager.DeviceManager;
import com.DKCloudID.crypt.ApduTransceive;

import java.io.IOException;

public class SamVIdCard {
    public static final int NUMBER_OF_REPARSING = 5;              /*解析失败时，重新解析的次数*/

    public DeviceManager deviceManager;
    public NfcB nfcB = null;

    public SamVIdCard(DeviceManager deviceManager, NfcB nfcB) {
        this.deviceManager = deviceManager;
        this.nfcB = nfcB;

        ApduTransceive.setTag(nfcB);
    }

    public void close() throws CardNoResponseException{
        try {
            nfcB.close();
        } catch (IOException e) {
            throw new CardNoResponseException(e.getMessage());
        }
    }

    public void connect() throws CardNoResponseException{
        try {
            if (!nfcB.isConnected()) {
                nfcB.connect();
            }
        } catch (IOException e) {
            throw new CardNoResponseException(e.getMessage());
        }
    }

    /**
     * 获取云解码初始化数据
     * @return         云解码初始化数据
     * @throws CardNoResponseException
     *                  操作无响应时会抛出异常
     */
    public byte[] getSamVInitData() throws CardNoResponseException {
        byte[] initData = deviceManager.msgCrypt.getDnData();
        if (initData == null) {
            if ( !nfcB.isConnected() ) {
                throw new CardNoResponseException("身份证已拿开");
            }
            else {
                throw new CardNoResponseException("身份证读取错误");
            }
        }

        return initData;
    }

    /**
     * 指令传输，同步阻塞方式
     * @param data     发送的数据
     * @return         返回的数据
     * @throws CardNoResponseException
     *                  操作无响应时会抛出异常
     */
    public synchronized byte[] transceive(byte[] data) throws CardNoResponseException {
        byte[] msgReturnBytes = deviceManager.msgCrypt.analyze(data);
        if (msgReturnBytes == null) {
            if ( !nfcB.isConnected() ) {
                throw new CardNoResponseException("身份证已拿开");
            }
            else {
                throw new CardNoResponseException("身份证读取错误");
            }
        }

        return msgReturnBytes;
    }
}
